package com.bms.api.base.aspect;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.bms.common.base.common.util.JsonUtil;
import com.feilong.core.date.DateExtensionUtil;

import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;

@Aspect
@Component
@Log4j2
public class WebLogAspect {
	
	@Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
	public void logPointCut() {
	}

	@Around("logPointCut()")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		MethodSignature signature = (MethodSignature) pjp.getSignature();
		Method method = signature.getMethod();
		HttpServletRequest request = attributes.getRequest();
		ApiOperation operation = method.getAnnotation(ApiOperation.class);
		log.info("请求方法 : " + operation.value());
		log.info("地址 : " + request.getRequestURL().toString());
		
		StringBuilder params = new StringBuilder();
		for(Object arg : pjp.getArgs()){
			params.append(JsonUtil.getJsonFromObject(arg));
			params.append("&");
		}
		log.info("参数 : " + params.toString().substring(0, params.toString().length()-1));
		Date beginDate = new Date();
		Object ob = pjp.proceed();
		log.info("耗时 : " + DateExtensionUtil.formatDuration(beginDate));
		log.info("==================================================");
		return ob;
	}
}
